<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="start">开始</button>
    <button id="cancel">结束</button>
    <script>
        const startBtn = document.querySelector('#start')
        const cancelBtn = document.querySelector('#cancel')
        // 取消promise
        class CancelToken {
            constructor(cancelFn) {
                this.promise = new Promise((resolve, reject) => {
                    cancelFn(() => {
                        setTimeout(console.log, 0, 'delay cancelled')
                        resolve()
                    })
                })
            }
        }
        function cancellableDelayedResolve(delay) {
            setTimeout(console.log, 0, 'set delay')
            return new Promise((resolve, reject) => {
                const id = setTimeout(() => {
                    setTimeout(console.log, 0, 'delayed resolve')
                    resolve()
                }, delay)
                const cancelToken = new CancelToken((cancelCallback) => {
                    cancelBtn.addEventListener('click', cancelCallback)
                })
                cancelToken.promise.then(() => {
                    clearTimeout(id)
                })
            })
        }
        startBtn.addEventListener('click', () => cancellableDelayedResolve(1000))
    </script>
</body>

</html>